<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@page import="java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.*" %>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Student Edit Department</title>
	<link rel="stylesheet" type="text/css" href="css/stylev2.css" />
	<link rel="stylesheet" type="text/css" href="css/student-system.css" />
	
	<style type="text/css">
		a {
	      text-decoration:none;
	   }
	</style>

</head>
<body>

<%	
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
			
	if (htp_session == null || htp_session.getAttribute("sUser") == null) {
	    // Forward the control to login.jsp if authentication fails or session expires
	    request.getRequestDispatcher("/login.jsp").forward(request,
	        response);
	}
	
	if("admin".equals(htp_session.getAttribute("sUser"))){%>
	<script>alert("This user dont have PERMISSION to access this zone.");</script>
	<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=admin_home.jsp"> 	
	<%}
	
	//////////get permission ///////////
	
	String name = String.valueOf(session.getAttribute("name"));
	String surname = String.valueOf(session.getAttribute("surname"));
	String role_name = String.valueOf(session.getAttribute("student_role"));
	
	String department_id2 = String.valueOf(session.getAttribute("department_id"));

	System.out.println("name : " + name);///////////////////////////////
	System.out.println("department_id : " + department_id2);/////////////////////////
	
	
	List<String> system_name = new ArrayList<String>();
	
	Permission permission = new Permission(strUser,name);
	permission.setDepartmentId(department_id2);
	permission.setStudentCreate(Boolean.valueOf(String.valueOf(session.getAttribute("student_create"))));
	permission.setStudentDelete(Boolean.valueOf(String.valueOf(session.getAttribute("student_delete"))));
	permission.setStudentRead(Boolean.valueOf(String.valueOf(session.getAttribute("student_read"))));
	permission.setStudentUpdate(Boolean.valueOf(String.valueOf(session.getAttribute("student_update"))));
	
	String permiss = "";
	if(permission.getStudentCreate()) {
		permiss = permiss + "Add";
	}
	if(permission.getStudentUpdate()) {
		if("".equals(permiss)) {
			permiss = permiss + "Edit";
		} else {
			permiss = permiss + " Edit";
		}
	}
	if(permission.getStudentRead()) {
		if("".equals(permiss)) {
			permiss = permiss + "Read";
		} else {
			permiss = permiss + " Read";
		}
	}
	if(permission.getStudentDelete()) {
		if("".equals(permiss)) {
			permiss = permiss + "Delete";
		} else {
			permiss = permiss + " Delete";
		}
	}
	//check permission
	if(!permission.getStudentUpdate()){%>
		<script>alert("This user dont have PERMISSION to access this zone.");</script>
		<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=student_home.jsp"> 	
	<%}
	
	// get paremeter
	String studentId = request.getParameter("student_id");

	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps + "&characterEncoding=tis620" );
	
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
	/* find department in database */
	List<Department> department = new ArrayList<Department>();
	String department_name = "";
	int department_id = -1;
	
	try {			   
		ResultSet rs_department = connect.createStatement().executeQuery("SELECT department_id, department_name_th " 
				+ " FROM department " + " ORDER BY department_id");
		
		while(rs_department.next()) {
			Department dep = new Department();
			
			dep.setDepartmentNameTH(rs_department.getString("department_name_th"));
			dep.setDepartmentId(Integer.parseInt(rs_department.getString("department_id")));
			
			department.add(dep);
			
			// find department old
			ResultSet rs = connect.createStatement().executeQuery("SELECT D.department_name_th, D.department_id " 
					+ " FROM student S, department D " 
					+ " WHERE S.department_id=D.department_id"
					+ " AND student_id='"+studentId+"'");
			
			if(rs.next()) {
				department_name = rs.getString("department_name_th");
				department_id = rs.getInt("department_id");				
			}
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}
	
%>

<div id="page-wrap">
		<div id="inside">
			<table border="0">
				<tr style="font-size:24px">
					<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
						<div id="header_banner-2"></div>
					</td>
					
					<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
						<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
						<a href="logout.jsp"><p align="right"><label style="cursor: pointer;"><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
					</td>
				</tr>
			</table>
				
				<div id="main-content-ac">
					<br><br><br><br>
				
						<center>
							<table width="800" border="0">
								<form method="post" id="form">
									<input type="hidden" id="student_id" name="student_id" value="<%=studentId %>" />
						            <input type="hidden" id="department_id_old" name="department_id_old" value="<%=department_id %>" />
						            
						       		<tr style="font-size:24px">
						              <td width="400" height="50"><label><font size="5"><strong>ภาควิชา (เดิม)</strong></font> </label></td>
						              <td width="400" height="50"><label><font size="5"> <%=department_name %> </font></label></td>
						            </tr>
						            
						            <tr style="font-size:24px">
						              <td height="50">
						              		<label> <font size="5"><strong>ภาควิชา (ใหม่)</strong></font> </label>
				         					<label><font size="5" color="#FF0000">*</font></label>
				         			  </td>
						              <td height="50">
						              	<select name="department" style="font-size:18px">
						                        <option value="select">Select</option>
	<%
													for(Department dept : department) {
														if(dept.getDepartmentId() == 0 || dept.getDepartmentId() == department_id) {
															
														}
														else {
	%>
															<option value="<%=dept.getDepartmentId()%>" id="<%=dept.getDepartmentId()%>"><%=dept.getDepartmentNameTH()%></option>	
	<%												
														}
													}
	%>
						            	</select>
						              </td>
						            </tr>
						            
						            <tr style="font-size:24px">
						                <td height="50"><label><font size="3" color="#FF0000">หมายเหตุ: * คือ ข้อมูลสำคัญ จำเป็นต้องกรอก</font></label></td>
						                <td height="50">
						                </td>
						            </tr>
						            
						            <tr style="font-size:24px">
						                <td height="50"><center><input type="submit" name="save" id="save" value="save" class="buttonStyle" /></center></td>
						        </form>
						                <td height="50">
						                	<a href="student_edit.jsp"><button class="buttonStyle">cancel</button></a>
						                </td>
						            </tr>
							</table>
						</center>
						
						<br><br><br>
				
				
			<div style="clear: both;"></div>
				
			<div id="footer"></div>
			
		</div>		
			<div style="clear: both;"></div>		
   </div>

<%
		String checkButton = request.getParameter("save");
		System.out.println("checkButton : "+checkButton);////////////////////try///////////////////
		// check save button is pressed
		if("save".equals(checkButton)) {
			// get value from tag
			String student_id = request.getParameter("student_id");
			String department_old = request.getParameter("department_id_old");
			String department_new = request.getParameter("department");
			
			try {											 
				connect.createStatement().executeUpdate("UPDATE `student` SET department_id="+department_new+" "
													+ ", department_id_old="+department_old+", transfer="+1+" "
													+ " WHERE student_id='"+student_id+"'");
				
				/* Log file */						
				String log = strUser+" "+name+" "+surname+" edit student";
				Log.writeAdminFile(log);

%>
				<script language="javascript"> alert("บันทึกข้อมูลสำเร็จ");	</script>
				<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=student_edit.jsp">
				
<%
			} catch (SQLException e) {
				e.printStackTrace();
			}				
			
		}
		
		connect.close();
%>

</body>
</html>